package com.log6z.dashborad.config;


import com.log6z.dashborad.constant.GatewayConstant;
import com.log6z.dashborad.domain.DefaultAbstractUser;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;


/**
 * 流程管控组件基础拦截器
 */
@Slf4j
@Component
public class LogisticsCtrlBaseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        DefaultAbstractUser defaultAbstractUser = handleDefaultAbstractUser(request);
        LoginContext.setDefaultAbstractUserThreadLocal(defaultAbstractUser);
        return true;
    }

    /**
     * 处理网关请求，获取传递过来的header中的用户信息
     * @param request
     * @return
     */
    private DefaultAbstractUser handleDefaultAbstractUser(HttpServletRequest request){

        DefaultAbstractUser defaultAbstractUser = new DefaultAbstractUser();
        defaultAbstractUser.setToken(request.getHeader(GatewayConstant.TOKEN));
        defaultAbstractUser.setCorpId(str2Int(request.getHeader(GatewayConstant.REQUEST_HEADER_CORP_ID)));
        defaultAbstractUser.setWebgisUserId(str2Int(request.getHeader(GatewayConstant.REQUEST_HEADER_WEBGIS_USER_ID)));
        defaultAbstractUser.setUserId(str2Long(request.getHeader(GatewayConstant.REQUEST_HEADER_USER_ID)));
        defaultAbstractUser.setUserName(request.getHeader(GatewayConstant.REQUEST_HEADER_USER_NAME));
        defaultAbstractUser.setUserSourceType(str2Int(request.getHeader(GatewayConstant.REQUEST_HEADER_SOURCE_TYPE)));
        defaultAbstractUser.setParentId(str2Int(request.getHeader(GatewayConstant.REQUEST_HEADER_PARENT_ID)));
        defaultAbstractUser.setOrgId(str2Int(request.getHeader(GatewayConstant.REQUEST_HEADER_ORG_ID)));
        defaultAbstractUser.setOrgName(request.getHeader(GatewayConstant.REQUEST_HEADER_ORG_NAME));

        //放入诊断日志
        MDC.put(GatewayConstant.TOKEN, defaultAbstractUser.getToken());
        MDC.put(GatewayConstant.REQUEST_HEADER_CORP_ID, String.valueOf(defaultAbstractUser.getCorpId()));
        MDC.put(GatewayConstant.REQUEST_HEADER_USER_ID, String.valueOf(defaultAbstractUser.getUserId()));

        return defaultAbstractUser;
    }

    /**
     * String转Integer
     * @param strValue
     * @return
     */
    private Integer str2Int(String strValue){
        if(Objects.isNull(strValue)) {
            return null;
        }else {
            return Integer.parseInt(strValue);
        }
    }

    /**
     * String转Long
     * @param strValue
     * @return
     */
    private Long str2Long(String strValue){
        if(Objects.isNull(strValue)) {
            return null;
        }else {
            return Long.parseLong(strValue);
        }
    }

}
